package common.code;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javassist.Modifier;

public class DaoUtils {
	
	/**
	 * 将ResultSet转化为List<BO>
	 * @param rs
	 * @param boClass
	 * @return
	 * @throws SQLException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 */
	public static List resultSetToBOList(ResultSet rs,Class boClass) throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException, IllegalArgumentException, InvocationTargetException
	{
		List result=new ArrayList();
		if(rs!=null)
		{
			ResultSetMetaData metaData=rs.getMetaData();
			List nameList=new ArrayList();
			for(int i=1;i<=metaData.getColumnCount();i++)
			{
				nameList.add(metaData.getColumnName(i).toLowerCase().replaceAll("_", ""));
			}
			while(rs.next())
			{
				Object bo=Class.forName(boClass.getName()).newInstance();
				Method[] methods=bo.getClass().getDeclaredMethods();
				for(int i=0;i<methods.length;i++)
				{
					if(!Modifier.isPrivate(methods[i].getModifiers()) && methods[i].getName().startsWith("set"))
					{
						//取得不包含set的名称
						String name=methods[i].getName().substring(3).toLowerCase();
						if(nameList.contains(name))
						{
							int index=nameList.indexOf(name);
							Class[] paramClass=methods[i].getParameterTypes();
							methods[i].invoke(bo, getMethodValues(paramClass[0],index,rs));
						}
					}
				}
				result.add(bo);
			}
			
		}
		
		return result;
	}
	
	
	/**
	 * 根据参数的类型和参数的index，获得值
	 * @param paramClass
	 * @param index
	 * @param rs
	 * @return
	 * @throws SQLException
	 */
	private static  Object[] getMethodValues(Class paramClass,int index,ResultSet rs) throws SQLException
	{
	   Object[] objs;
	   if(paramClass==String.class)
	   {
		   objs=new Object[]{rs.getString(index+1)};
	   }
	   else if(paramClass==Long.class)
	   {
		   objs= new Object[]{new Long(rs.getLong(index+1))};
	   }
	   else if(paramClass==Double.class)
	   {
		   objs= new Object[]{new Double(rs.getDouble(index+1))};
	   }
	   else if(paramClass==Date.class)
	   {
		   objs= new Object[]{rs.getTimestamp(index+1)};
	   }
	   else
	   {
		   objs=new Object[]{};
		   throw new RuntimeException("不支持此类型==============="+paramClass.getName());
	   }
		
		return objs;
	}

}
